/**
 * @author Kostya
 */

var iWindow = null;
var iStatusBar = null;

var iOpener = null;

Ext.onReady(function(){
	iOpener = Ext.air.NativeWindow.getRootHtmlWindow();
	Ext.QuickTips.init();
	
	iWindow = window.nativeWindow;
	
	iStatusBar = new Ext.StatusBar({
		defaultText: 'Idle',
		region: 'south'
	});
	
	iNetworkListener = function(aNetwork){
		lGoButton.setDisabled(aNetwork);
	}
	
	var lPasswordText = new Ext.form.TextField({
		fieldLabel: 'Password',
		enableKeyEvents: true,
		allowBlank: true,
		msgTarget: 'under',
		inputType: 'password',
		value: ''
	});
		
	lPasswordText.on('keydown', function(item, evt){
		if(evt.getKey()==Ext.EventObject.ENTER){
			lGoHandler();
		}
	});
		
	var lSavePassword = new Ext.form.Checkbox({
		enableKeyEvents: true,
		fieldLabel: 'Save password'
	});
	
	var lGoHandler = function(){
		air.trace('Submitting...');
		var password = hex_md5(lPasswordText.getValue());
		callAPI(iOpener.iSessionRecord.get('server'), 'user.CheckUserNamePassword', {
			userName: iOpener.iSessionRecord.get('login'),
			password: password
		}, function(aXML){
			air.trace('password: token: '+aXML.documentElement.getAttribute('token'));
//			iOpener.newSessionCreated(lServerText.getValue(), lLoginText.getValue(), 
//					aXML.documentElement, lSavePassword.getValue());
			iOpener.afterAskPassword(aXML.documentElement.getAttribute('token'),
					lSavePassword.getValue());
			iWindow.close();
		}, function(){
			lPasswordText.setValue('');
			lPasswordText.focus();
		});
	}
	
	var lGoButton = new Ext.Button({
		enableKeyEvents: true,
		text: 'Login',
		handler: lGoHandler
	});
	
	var lSessionForm = new Ext.form.FormPanel({
		frame: true,
		region: 'center',
		minButtonWidth: 100,
		labelAlign: 'right',
		defaults: {
			anchor: '100%'
		},
		items:[lPasswordText, lSavePassword],
		buttons:[lGoButton]
	});
	
	var lViewport = new Ext.Viewport({
		layout: 'border',
		items: [lSessionForm, iStatusBar]
	});
	
	iWindow.visible = true;
	iWindow.activate();
	
	lViewport.doLayout();
	
	lPasswordText.focus();
});
